package IPADistribution.Servlets;

import IPADistribution.Constant.Constant;
import IPADistribution.PlistUtil.PlistUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;


interface FileUploadSucceedCallback {
    void fileUploadSucceedCallback(String fileurl) throws ServletException, IOException;
}


@WebServlet(name = "Upload")
public class Upload extends HttpServlet {
    public static String env_key = "env";
    public static String ipa_key = "ipa";
    public static String ipaName_key = "ipaName";
    public static String bundleIdentifer_key = "bundleIdentifer";
    public static String bundleVersion_key = "bundleVersion";

    private ServletFileUpload upload;
    private HashMap paramMap;
    private  String host;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        host = request.getHeader("host");

        DiskFileItemFactory factory = new DiskFileItemFactory();
        File repository = (File)request.getServletContext().getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

        upload = new ServletFileUpload(factory);
        try {
            List<FileItem> items = upload.parseRequest(request);
            //验证参数
            paramMap = paramMapFromItems(items);
            if (!isRequestParamValid(paramMap)) {
                response.getWriter().write("param invalid!\n");
                return;
            }

            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()){
                FileItem i = iterator.next();
                if (i.isFormField()) {
                    //表单数据
                    processForm(i);
                }else  {
                    //二进制数据
                    processData(i, response, new FileUploadSucceedCallback() {
                        @Override
                        public void fileUploadSucceedCallback(String fileurl) throws ServletException, IOException {
                            //生成plist
                            PlistUtil.generatePlist(items, request.getServletContext(), fileurl);
                        }
                    });
                }
            }

        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }

    private void processForm(FileItem item) {
        //String field = item.getFieldName();
        //String value = item.getString();
    }

    private  void  processData(FileItem item, HttpServletResponse response, FileUploadSucceedCallback callback) throws IOException, FileUploadException {
        //字段名
        //String field = item.getFieldName();
        //文件名
        String fileName = item.getName();
        fileName = FilenameUtils.getName(fileName); //取文件名,有的浏览器可能包含路径

        Date now = new Date();
        String date = new SimpleDateFormat("yyyy-MM-dd").format(now);
        String ipaDir = Constant.ipa_path + File.separator +paramMap.get(bundleVersion_key) +
                File.separator + paramMap.get(env_key).toString().toUpperCase() + File.separator + date;
        String realIpaDir = getServletContext().getRealPath(ipaDir);

        File ipaDirector = new File(realIpaDir);
        if (!ipaDirector.exists()) {
            ipaDirector.mkdirs();
        }

        String ipaFilePath = ipaDir + File.separator + fileName;
        File ipaFile = new File(getServletContext().getRealPath(ipaFilePath));
        if (!ipaFile.exists()){
            ipaFile.createNewFile();
        }

        try {
            item.write(ipaFile);
            if (callback != null) {
                String ipaUrl = "http://"+host+ "/" + ipaFilePath;
                callback.fileUploadSucceedCallback(ipaUrl);
                response.getWriter().write("file upload succeed!\n");
            }else {
                response.getWriter().write("file upload succeed!\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("file upload failed!\n");
        }

    }

    private boolean isRequestParamValid(HashMap paramMap) {
        Set fieldSet = paramMap.keySet();
        boolean envValid = paramMap.get(env_key).toString().toUpperCase().equals("DEV")||
                paramMap.get(env_key).toString().toUpperCase().equals("TEST")||
                paramMap.get(env_key).toString().toUpperCase().equals("RELEASE");

        return fieldSet.contains(ipa_key) &&
                fieldSet.contains(ipaName_key) &&
                fieldSet.contains(bundleIdentifer_key) &&
                fieldSet.contains(bundleVersion_key) &&
                envValid;
    }

    private HashMap paramMapFromItems(List<FileItem> items) throws UnsupportedEncodingException {
        HashMap paramMap = new HashMap();
        for (FileItem item : items) {
            String field = item.getFieldName();
            String value = item.isFormField()?item.getString("UTF-8"):item.getName();
            if (value!=null){
                paramMap.put(field, value);
            }
        }
        System.out.println("map="+paramMap);
        return paramMap;
    }
}
